//
// Created by dddgzc on 2025/1/23.
//

#include "Atlas.h"

#include <format>

void Atlas::loadFromFile(const char* pathTemplate, int num) {
    char path[1024] = {};
    for (int i = 1; i <= num; i++) {
        sprintf(path, pathTemplate, i);
        SDL_Surface* surface = IMG_Load(path);
        SDL_Texture* texture = SDL_CreateTextureFromSurface(mainRenderer, surface);
        images.push_back(texture);
        SDL_FreeSurface(surface);
    }
}

void Atlas::loadFromFileFlip(const char *pathTemplate, int num) {
    char path[1024] = {};

    for (int i = 1; i <= num; i++) {
        sprintf(path, pathTemplate, i);
        SDL_Surface* srcSurface = IMG_Load(path);
        SDL_Surface* flippedSurface = SDL_CreateRGBSurface(0, srcSurface->w, srcSurface->h, srcSurface->format->BitsPerPixel,
                                                srcSurface->format->Rmask, srcSurface->format->Gmask,
                                                srcSurface->format->Bmask, srcSurface->format->Amask);
        for (int y = 0; y < srcSurface->h; y++) {
            for (int x = 0; x < srcSurface->w; x++) {
                Uint32 pixel = ((Uint32*)srcSurface->pixels)[y * srcSurface->w + x];
                int newX = srcSurface->w - x - 1;
                ((Uint32*)flippedSurface->pixels)[y * flippedSurface->w + newX] = pixel;
            }
        }
        SDL_Texture* texture = SDL_CreateTextureFromSurface(mainRenderer, flippedSurface);
        images.push_back(texture);
        SDL_FreeSurface(srcSurface);
        SDL_FreeSurface(flippedSurface);
    }
}

void Atlas::clearImages() {
    images.clear();
}

SDL_Texture *Atlas::getImage(int index) const{
    if (index >= images.size() || index < 0) return nullptr;
    return images[index];
}

int Atlas::getSize() const {
    return images.size();
}

void Atlas::addImage(SDL_Texture *texture) {
    images.push_back(texture);
}




